# /etc/profile

# /run is not automatically created by guix
mkdir /run

# Quick access to $GUIX_ENVIRONMENT, for usage on config files
# (currently only /etc/nginx/nginx.conf)
ln -s $GUIX_ENVIRONMENT /env

# Link every file in /usr/etc on /etc
ls -1d /usr/etc/* | while read filepath; do
    ln -s $filepath /etc/
done

# Guix' php-fpm and nginx use its installation path as prefix
# This is a containerized application, we don't want that
alias php-fpm='php-fpm -c /etc/php.ini -p ""'
alias nginx='nginx -c "/etc/nginx/nginx.conf" -p "/tmp"'

# To avoid nginx init errors
mkdir /tmp/logs

start () {
    mysqld_safe 1>/dev/null &
    php-fpm
    nginx
}

stop () {
    nginx -s stop
    mysqladmin shutdown
    killall php-fpm
}

# Random password generator
# @param $1 password length
randpw () {
    head /dev/urandom | tr -dc '_?!#A-Za-z0-9' | head -c $1 ; echo ''
}

## Install MariaDB on first run
if [ ! -d /var/lib/mysql/data/mysql ]; then
    # Awful hack, required to solve a bug on mariadb guix' package
    lc_messages_dir=$(find /gnu/store -type d -name english | grep mysql)
    sed -i -e "s|#lc_messages_dir#|$lc_messages_dir|" /usr/etc/my.cnf

    mysql_root_password=$(randpw 24)
    mysql_install_db
    mysqld_safe &
    sleep 3
    mysql -sf << EOF
# set root password
UPDATE mysql.user SET Password=PASSWORD('$mysql_root_password') WHERE User='root';
# remove anonymous user
DELETE FROM mysql.user WHERE User='';
# remove remote root
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
# remove test database
DROP DATABASE IF EXISTS test; DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
# reload privilege tables
FLUSH PRIVILEGES;
EOF
    sed -i -e "s|# password|password = $mysql_root_password|" /usr/etc/my.cnf
    mysqladmin shutdown
fi

cat << EOF

  ____ _   _ _   _    ____       _
 / ___| \ | | | | |  / ___|_   _(_)_  __
| |  _|  \| | | | | | |  _| | | | \ \/ /
| |_| | |\  | |_| | | |_| | |_| | |>  <
 \____|_| \_|\___/   \____|\__,_|_/_/\_\\

Welcome! 'start' or 'stop' services using that same words as commands.

EOF
